package com.ljl.forum_1.exception;

import com.ljl.forum_1.common.AppResult;
import com.ljl.forum_1.common.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Keafmd
 * 全局异常处理
 * @ClassName: GlobalExceptionHandler
 * @Description: GlobalExceptionHandler
 * @author: lijl
 * @date: 2025/1/25 20:40
 * @Blog: https://keafmd.blog.csdn.net/
 */

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler{

    @ResponseBody
    @ExceptionHandler(ApplicationException.class)
    public AppResult applicationExceptionHandler (ApplicationException e) {
        // 打印异常现象
        e.printStackTrace();
        // 打印日志
        log.error(e.getMessage());
        if(e.getErrorResult() != null){
            return e.getErrorResult();
        }

        // 非空校验
        if(e.getMessage() == null || e.getMessage().equals("")){
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }

        // 返回具体异常现象
        return AppResult.failed(e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public AppResult exceptionHandler(Exception e) {
        // 打印异常信息
        e.printStackTrace();
        // 打印日志
        log.error(e.getMessage());
        // 非空校验
        if(e.getMessage() == null || e.getMessage().equals("")) {
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }
        // 返回异常信息
        return AppResult.failed(e.getMessage());
    }
}
